package win.zxshuo.www.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.stereotype.Service;
import win.zxshuo.www.model.CategoryModel;
import win.zxshuo.www.repository.CategoryRepository;

import java.util.Date;
import java.util.List;
import java.util.Optional;

@Service
@Configurable
public class CategoryService {
    @Autowired
    CategoryRepository categoryRepository;

    public List<CategoryModel> getAllCategories(){
        return categoryRepository.findAll();
    }

    public Optional<CategoryModel> getNameById(Long id){
        Optional<CategoryModel> categoryModel = categoryRepository.findById(id);
        return categoryModel;
    }

    public CategoryModel getCategoryByName(String name){
        CategoryModel categoryModel = categoryRepository.getByName(name);
        if (categoryModel == null){
            CategoryModel categoryModel1 = new CategoryModel();
            categoryModel1.setCreateDate(new Date());
            categoryModel1.setModifyDate(new Date());
            categoryModel1.setName(name);
            categoryRepository.save(categoryModel1);
            return categoryModel1;
        }else {
            return categoryModel;
        }
    }

    public Long getCategoryIdByName(String name){
        CategoryModel categoryModel = categoryRepository.getByName(name);
        if (categoryModel == null){
            CategoryModel categoryModel1 = new CategoryModel();
            categoryModel1.setCreateDate(new Date());
            categoryModel1.setModifyDate(new Date());
            categoryModel1.setName(name);
            categoryRepository.save(categoryModel1);
            return categoryModel1.getId();
        }else {
            return categoryModel.getId();
        }
    }


}
